package com.houkunlin.configuration;

import com.baomidou.mybatisplus.extension.plugins.handler.DataPermissionHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.DataPermissionInterceptor;
import net.sf.jsqlparser.expression.Expression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import java.util.List;

/**
 * MyBatis Plus 拦截器配置
 *
 * @author HouKunLin
 */
@Configuration
public class MybatisPlusInterceptorConfig {
    /**
     * 数据权限处理器列表
     */
    private final List<DataPermissionHandler> handlers;

    public MybatisPlusInterceptorConfig(final List<DataPermissionHandler> handlers) {
        this.handlers = handlers;
    }

    /**
     * 增加数据权限拦截器配置
     */
    @Order(Ordered.HIGHEST_PRECEDENCE)
    @Bean
    public DataPermissionInterceptor dataPermissionInterceptor() {
        return new DataPermissionInterceptor((where, mappedStatementId) -> {
            Expression last = where;
            for (final DataPermissionHandler expression : handlers) {
                last = expression.getSqlSegment(last, mappedStatementId);
            }
            return last;
        });
    }
}
